<?php

class FP_Model_Collection implements Iterator, Countable
{
  protected $_model_class = 'FP_Model';
  protected $_gateway = null;
  protected $_collection = null;
  protected $_count = null;

  public function __construct($pItems, $pGateway, $pModelClass=null){
    if ($pModelClass)
	$this->_model_class = $pModelClass;
    $this->setGateway($pGateway);
    $this->setCollection($pItems);
  }

  public function setGateway($pGateway){
    $this->_gateway = $pGateway;
    return $this;
  }

  public function getGateway(){
    return $this->_gateway;
  }

  public function setCollection($pItems){
    $this->_collection = $pItems;
  }

  public function getCollection(){
    return $this->_collection;
  }

  public function count(){
    if ($this->_count === null)
      $this->_count = count($this->_collection);
    return $this->_count;
  }

  public function current(){
    if ($this->_collection instanceof Iterator)
      $key = $this->_collection->key();
    else
      $key = key($this->_collection);

    if ($key === null)
      return false;

    $item = $this->_collection[$key];

    try {
//     logdebug('FP_Model_Collection.current: item=' . $item);
    if (is_array($item) || (get_class($item) != $this->_model_class) && !is_subclass_of($item, $this->_model_class)){
      $ModelClass = $this->_model_class;
      $item = new $ModelClass($item, $this->_gateway);
      $this->_collection[$key] = $item;
    }
    } catch (Exception $x){

	logexception($x);

    }

    return $item;
  }

  public function key(){
    return key($this->_collection);
  }

  public function next(){
    return next($this->_collection);
  }

  public function rewind(){
    return reset($this->_collection);
  }

  public function valid(){
    return $this->current() !== false;
  }

  public function _toArray($pCollection){
    $collection = array();
    foreach ($pCollection as $item) {
      if ($item instanceof FP_Model || $item instanceof FP_Model_Collection)
	$collection[] = $item->toArray();
      else
	$collection[] = $item;
    }
    return $collection;

  }

  public function toArray(){
    return $this->_toArray($this->_collection);
  }
}

?>